<!--
  @description 商品分类管理
  @author cjs
  @date 2021-07-17 09:33:40
-->
<template>
  <div class="app_container">
    <div class="baseBorderRadius baseBoderShadow bgWhite">
      <select-element
        :search-list="searchList"
        :search-data="searchData"
        :init-search-data="initSearchData"
        :search-obj="searchObj"
        @search="searchFunc"
        @reset="resetFunc"
      >
        <template v-slot:zzjgId="{ scope }">
          <select-depart v-model="scope.zzjgId" />
        </template>
      </select-element>

      <div class="handle_wrap">
        <el-button
          type="primary"
          @click="addFunc"
        >新 增</el-button>
      </div>
      <div class="table_wrap">
        <div class="table_box">
          <c-table
            :has-check="false"
            :thead-data="theadData"
            :table-data="tableData"
            :is-one-line="false"
            border
          >
            <template v-slot:ope="{ scope }">
              <div>
                <el-link type="primary" size="mini" round @click="editRowFunc(scope.row)">编辑</el-link>
                <el-link type="warning" size="mini" round @click="deleteRowFunc(scope.row)">删除</el-link>
                <el-link type="danger" size="mini" round @click="addProdectFunc(scope.row)">添加商品</el-link>
              </div>
            </template>
          </c-table>
        </div>
        <div class="page_box">
          <el-pagination
            v-show="totalSize"
            background
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 新增/编辑弹出层 -->
    <el-dialog
      title="维护商品分类"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <div>
        <el-form
          ref="form_ref"
          :model="formData"
          :rules="rules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item
            label="商品分类"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              v-blurTrim
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="标签"
            prop="tag"
          >
            <el-input
              v-model="formData.tag"
              v-blurTrim
              placeholder="请输入"
            />
          </el-form-item>
          <!-- <el-form-item label="所属商铺"
					  prop="zzjgId">
						<select-depart v-model="formData.zzjgId" />
					</el-form-item> -->
          <el-form-item
            label="是否新品"
            prop="isNew"
          >
            <div class="special_switch_wrap">
              <el-switch
                v-model="formData.isNew"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
          </el-form-item>
          <el-form-item
            label="是否上架"
            prop="status"
          >
            <div class="special_switch_wrap">
              <el-switch
                v-model="formData.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </div>

          </el-form-item>
          <el-form-item
            label="排序号"
            prop="sortNumber"
          >
            <el-input
              v-model="formData.sortNumber"
              v-blurTrim
              v-num
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="分类icon"
            prop="icon"
          >
            <el-input
              v-model="formData.icon"
              v-blurTrim
              placeholder="分类icon（示例 HOT/TOP）"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="saveFunc"
        >保存</el-button>
        <el-button @click="cancelFunc">取消</el-button>
      </div>
    </el-dialog>
    <!-- 添加商品的弹出层 -->
    <el-dialog title="维护商品" :visible.sync="dialogProduct" width="800px">
      <div>
        <div v-if="dialogProduct" class="table_wrap">
          <div class="table_box">
            <!-- <c-table ref="product_ref"
              v-model="checkProductList"
              :is-one-line="false"
              :thead-data="theadDataProduct"
              :table-data="tableDataProduct"
              :has-check="true"
              border
              row-key="id"
            /> -->
            <el-checkbox-group v-model="checkProductList" @change="handleCheckChange">

              <template v-for="(item, index) in tableDataProduct">
                <!-- <div class="product-item" :key="index"> -->
                <el-checkbox :key="index" :label="item.id" border>{{ item.name }}</el-checkbox>
                <!-- </div> -->
              </template>
            </el-checkbox-group>
          </div>
          <div class="page_box">
            <el-pagination
              v-show="totalSizeProduct"
              background
              :current-page="currentPageProduct"
              :page-size="pageSizeProduct"
              layout="total, prev, pager, next, jumper"
              :total="totalSizeProduct"
              @size-change="handleSizeChangeProduct"
              @current-change="handleCurrentChangeProduct"
            />
          </div>
        </div>
        <div>选中的商品：</div>
        <div class="check_wrap">
          <transition-group
            name="list-complete"
            tag="span"
          >
            <template v-for="(item, index) in checkedList">
              <el-tag
                :key="index"
                size="small"
                closable
                draggable="true"
                title="拖动更换位置"
                @close="closeTag(item, index)"
                @dragstart.native="dragStartFunc(item, index)"
                @drop.native="dropFunc($event, index)"
                @dragover.native="dragOverFunc"
              >{{ item.name }}</el-tag>
            </template>
          </transition-group>
        </div>
        <div style="text-align: center;">
          <el-button type="primary" @click="addProductSureFunc">确定</el-button>
          <el-button @click="dialogProduct = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Table from "@/components/table/table.vue";
import SelectElement from "@/views/cold-drink/select-element.vue";
import SelectDepart from "@/views/cold-drink/select-depart.vue";
import {
  page,
  removeById,
  saveOrUpdate,
  selectById,
  addProductList
} from "@/api/product/product-type.js";
import {
  page as productPage,
  getProductList
} from "@/api/product/product.js";
export default {
  components: {
    "c-table": Table,
    "select-element": SelectElement,
    "select-depart": SelectDepart
  },
  data() {
    return {
      searchData: {
        name: "",
        zzjgId: "",
        isNew: "",
        status: ""
      },
      oldSearchData: {},
      initSearchData: {},
      // 查询列表
      searchList: [
        { label: "商品名称", element: "el-input", code: "name" },
        // {
        //   label: "所属商家",
        //   element: "el-cascader",
        //   code: "zzjgId",
        //   slotName: "zzjgId"
        // },
        { label: "是否新品", element: "el-select", code: "isNew" },
        { label: "是否上架", element: "el-select", code: "status" }
      ],
      searchObj: {
        isNew: [{ label: "是", value: 1 }, { label: "否", value: 0 }],
        status: [{ label: "是", value: 1 }, { label: "否", value: 0 }]
      },
      theadData: [
        { name: "序号", code: "index", width: 60 },
        { name: "分类名称", code: "name" },
        // { name: "所属店铺", code: "zzjgName" },
        { name: "图标", code: "icon" },
        { name: "标签", code: "tag" },
        { name: "是否新品", code: "isNewTxt" },
        { name: "排序号", code: "sortNumber" },
        { name: "是否上架", code: "statusTxt" },
        { name: "操作", code: "ope", slotName: "ope", width: 160 }
      ],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      // 新增商品分类的弹出层
      dialogVisible: false,
      initFormData: {},
      formData: {
        zzjgId: "",
        name: "",
        isNew: 0,
        icon: "",
        status: 1,
        sortNumber: "",
        tag: ""
      },
      rules: {
        name: [
          { required: true, message: "商品分类不能为空" },
          { max: 32, message: "商品分类不能多于32个字符" }
        ],
        sortNumber: [{ required: true, message: "排序号不能为空" }],
        tag: [{ max: 10, message: "标签不能超出10个字符" }]
      },
      editId: null,
      // 添加商品的弹出层
      dialogProduct: false,
      checkProductList: [],
      theadDataProduct: [
        { name: "序号", code: "index", width: "60px" },
        { name: "商品名称", code: "name" },
        { name: "价格", code: "price" }
      ],
      tableDataProduct: [],
      currentPageProduct: 1,
      pageSizeProduct: 10,
      totalSizeProduct: 0,
      oldCheckedList: [],
      checkedList: [],
      dragIndex: null,
      productObj: {}
    };
  },
  watch: {
    checkedList: {
      deep: true,
      handler() {
        this.setCheckProductList();
        return;
        const { checkedList, tableDataProduct } = this;
        // eslint-disable-next-line
        tableDataProduct.map(item => {
          if (checkedList.findIndex(vo => vo.id === item.id) > -1) {

          }
        });
      }
    }
  },
  created() {
    this.oldSearchData = {
      ...this.searchData
    };
    this.initSearchData = {
      ...this.searchData
    };
    this.initFormData = {
      ...this.formData
    };
  },
  mounted() {
    this.getAllData();
  },
  methods: {
    handleCheckChange() {
      const { checkProductList, tableDataProduct, checkedList } = this;
      const list = checkProductList;
      const filterList = tableDataProduct.filter(item => {
        if (list.indexOf(item.id) > -1) {
          return false;
        }
        return true;
      });
      filterList.map(item => {
        const index = checkedList.findIndex(vo => vo.id === item.id);
        if (index > -1) {
          this.checkedList.splice(index, 1);
        }
      });
      checkProductList.map(item => {
        const index = this.checkedList.findIndex(vo => vo.id === item);
        if (index === -1) {
          this.checkedList.push(this.productObj[item]);
        }
      });
    },
    setCheckProductList() {
      const { checkedList, tableDataProduct } = this;
      this.checkProductList = [];
      tableDataProduct.map(item => {
        const index = checkedList.findIndex(vo => vo.id === item.id);
        if (index > -1) {
          this.checkProductList.push(item.id);
        }
      });
    },
    /**
     * @name dragStartFunc
     * @description 开始拖拽方法
     * @author cjs1992
     * @date 2020-04-09 10:55:15
     */
    dragStartFunc(data, index) {
      this.dragIndex = index;
    },
    /**
     * @name dropFunc
     * @description 放下方法
     * @author cjs1992
     * @date 2020-04-09 10:55:30
     */
    dropFunc(ev, index) {
      ev.preventDefault();
      // 将拖动元素与本元素放到本元素之前
      const dragData = this.checkedList[this.dragIndex];
      if (this.dragIndex < index) {
        index += 1;
      }
      const obj = {
        id: -1,
        name: dragData.name,
        is_my_catch: true
      };
      this.checkedList.splice(this.dragIndex, 1, obj);
      // 插入
      this.checkedList.splice(index, 0, dragData);
      // 清除obj
      const obj_i = this.checkedList.findIndex(item => {
        return item.is_my_catch === true;
      });
      this.checkedList.splice(obj_i, 1);
    },
    /**
     * @name dragOverFunc
     * @description
     * @author cjs1992
     * @date 2020-04-09 10:55:42
     */
    dragOverFunc(ev) {
      ev.preventDefault();
    },
    /**
     * @name addProductSureFunc
     * @description 添加商品
     * @param {}
     * @author cjs
     * @date 2021-07-17 17:09:34
     */
    async addProductSureFunc() {
      // addProductList
      const categoryId = this.editId;
      const obj = {
        categoryId,
        coldProductDto: [
          // {
          //   categoryId: "",
          //   productId,
          //   sortNumber
          // }
        ]
      };
      this.checkedList.map((item, index) => {
        obj.coldProductDto.push({
          categoryId,
          productId: item.id,
          sortNumber: index + 1
        });
      });
      await addProductList(obj);
      this.$message({
        type: "success",
        message: "添加商品成功"
      });
      this.dialogProduct = false;
    },
    /**
     * @name closeTag
     * @description 删除选中某个产品
     * @param {}
     * @author cjs
     * @date 2021-07-17 16:10:20
     */
    closeTag(item, index) {
      this.checkedList.splice(index, 1);
    },
    /**
     * @name getProductList
     * @description 获取绑定的商品列表
     * @param {}
     * @author cjs
     * @date 2021-07-17 16:43:06
     */
    async getProductList() {
      const res = await getProductList({
        categoryId: this.editId
      });
      this.checkedList = (res.data || []).map(item => {
        return {
          id: item.productId,
          name: item.productName
        };
      });
      this.setCheckProductList();
    },
    /**
     * @name addProdectFunc
     * @description 添加商品
     * @param {}
     * @author cjs
     * @date 2021-07-17 16:01:04
     */
    async addProdectFunc(row) {
      this.editId = row.id;
      this.currentPageProduct = 1;
      this.getAllProductList();
      this.getProductList();
      this.dialogProduct = true;
    },
    /**
     * @name getAllProductList
     * @description 获取商品列表
     * @param {}
     * @author cjs
     * @date 2021-07-17 16:00:09
     */
    async getAllProductList() {
      const res = await productPage({
        pageNo: this.currentPageProduct,
        pageSize: this.pageSizeProduct
      });
      // eslint-disable-next-line
      let list = res.data.records || [];
      list.map((item, index) => {
        item.index = this.pageSizeProduct * (this.currentPageProduct - 1) + index + 1;
      });
      this.tableDataProduct = list;
      list.map(item => {
        this.productObj[item.id] = item;
      });
      this.totalSizeProduct = res.data.total;
      this.setCheckProductList();
    },
    /**
     * @name editRowFunc
     * @description 编辑行
     * @param {}
     * @author cjs
     * @date 2021-07-17 11:55:30
     */
    async editRowFunc(row) {
      this.editId = row.id;
      const res = await selectById({
        id: row.id
      });
      for (const key in this.formData) {
        this.$set(this.formData, key, res.data[key]);
      }
      this.dialogVisible = true;
      await this.$nextTick();
      this.$refs.form_ref.clearValidate();
    },
    /**
     * @name deleteRowFunc
     * @description 删除行
     * @param {}
     * @author cjs
     * @date 2021-07-17 11:55:58
     */
    async deleteRowFunc(row) {
      const { id } = row;
      await this.confirmFunc({
        msg: "您确定要删除该分类吗？删除后，不可恢复"
      });
      await removeById({
        id
      });
      this.$message({
        type: "success",
        message: "删除成功"
      });
      this.handleCurrentChange(1);
    },
    /**
     * @name addProductFunc
     * @description 添加商品
     * @param {}
     * @author cjs
     * @date 2021-07-17 13:09:13
     */
    addProductFunc() {},
    /**
     * @name getAllData
     * @description 获取所有数据
     * @param {}
     * @author cjs
     * @date 2021-07-17 10:16:50
     */
    async getAllData() {
      this.getTableData();
    },
    /**
     * @name getTableData
     * @description 获取列表数据
     * @param {}
     * @author cjs
     * @date 2021-07-17 10:17:04
     */
    async getTableData() {
      const obj = {
        ...this.oldSearchData,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      };
      const res = await page(obj);
      // eslint-disable-next-line
      let list = res.data.records || [];
      list.map((item, index) => {
        item.index = this.pageSize * (this.currentPage - 1) + index + 1;
        item.isNewTxt = item.isNew ? "是" : "否";
        item.statusTxt = item.status ? "是" : "否";
      });
      this.tableData = list;
      this.totalSize = res.data.total;
    },
    /**
     * @name saveFunc
     * @description 保存方法
     * @param {}
     * @author cjs
     * @date 2021-07-17 11:05:20
     */
    saveFunc() {
      this.$refs.form_ref.validate(async valid => {
        if (!valid) {
          return;
        }
        // eslint-disable-next-line
        let obj = {
          ...this.formData
        };
        let msg = "新增";
        if (this.editId) {
          obj.id = this.editId;
          msg = "保存";
        }
        const res = await saveOrUpdate(obj);
        this.$message({
          type: "success",
          message: `${msg}成功`
        });
        this.resetFunc();
        this.dialogVisible = false;
      });
    },
    /**
     * @name cancelFunc
     * @description 取消方法
     * @param {}
     * @author cjs
     * @date 2021-07-17 11:05:32
     */
    cancelFunc() {
      this.dialogVisible = false;
    },
    /**
     * @name handleCurrentChange
     * @description 切换页码
     * @param {}
     * @author cjs
     * @date 2021-07-17 10:15:54
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData();
    },
    /**
     * @name handleSizeChange
     * @description 切换每页展示条数
     * @param {}
     * @author cjs
     * @date 2021-07-17 10:16:24
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(1);
    },
    /**
     * @name searchFunc
     * @description 查询方法
     * @param {}
     * @author cjs
     * @date 2021-07-17 10:14:58
     */
    searchFunc(searchData) {
      this.oldSearchData = {
        ...searchData
      };
      this.handleCurrentChange(1);
    },
    /**
     * @name resetFunc
     * @description 重置方法
     * @param {}
     * @author cjs
     * @date 2021-07-17 10:15:25
     */
    resetFunc() {
      this.searchData = {
        ...this.initSearchData
      };
      this.searchFunc(this.searchData);
    },
    /**
     * @name addFunc
     * @description 新增按钮点击
     * @param {}
     * @author cjs
     * @date 2021-07-17 09:37:39
     */
    async addFunc() {
      this.editId = null;
      this.formData = {
        ...this.initFormData
      };
      this.dialogVisible = true;
      await this.$nextTick();
      this.$refs.form_ref.clearValidate();
    }
  }
};
</script>
<style lang="scss" scoped>
.table_wrap {
  padding: 10px 20px;
}
.check_wrap {
  border: 1px solid #e0e0e0;
  height: 100px;
  overflow-y: auto;
  padding: 10px;
  /deep/ {
    .el-tag {
      margin-right: 10px;
    }
  }
}
.list-complete-enter, .list-complete-leave-to
/* .list-complete-leave-active for below version 2.1.8 */ {
  opacity: 0;
  transform: translateY(30px);
}
.list-complete-leave-active {
  position: absolute;
}
.drag_item {
  transition: all 0.8s;
  // display: inline-block;
  // margin-right: 10px;
}
.list-complete-enter, .list-complete-leave-to
/* .list-complete-leave-active for below version 2.1.8 */ {
  opacity: 0;
  transform: translateY(30px);
}
.list-complete-leave-active {
  position: absolute;
}
.list-complete-move {
  transition: transform 0.8s;
}
</style>
